<template>
  <div class="app-container">
    <div class="app-layout">
      <div class="pane" style="width: 100%;">
        <div class="head">
          <span>蓝图列表</span>
        </div>
        <div class="body">
          <!-- 工具栏 -->
          <div class="table-tool-bar">
            <div>
              <el-button type="primary" icon="plus" @click="handleAdd" :loading="loading">新增蓝图</el-button>
              <el-button type="danger" :disabled="ids.length === 0" icon="delete" @click="handleDelete()" :loading="loading">
                删除
              </el-button>
            </div>
            <div>
              <el-input
                v-model="queryParams.keywords"
                style="width:320px"
                placeholder="输入蓝图名称进行搜索"
                class="input-with-select"
                @keyup.enter="handleQuery"
              >
                <template #append>
                  <el-button icon="search" @click="handleQuery" />
                </template>
              </el-input>
            </div>
          </div>

          <!-- 流程列表 -->
          <div>
            <el-table
              ref="dataTableRef"
              v-loading="loading"
              :data="blueprintDesignerList"
              highlight-current-row
              border
              height="calc(100vh - 260px)"
              @selection-change="handleSelectionChange"
            >
              <el-table-column type="selection" width="55" align="center" />
              <el-table-column label="蓝图名称" prop="name" align="left" min-width="120" />
              <el-table-column label="蓝图描述" prop="description" align="left" min-width="180" show-overflow-tooltip />
              <el-table-column label="发布状态" prop="status" align="center" width="100">
                <template #default="scope">
                  <el-tag :type="scope.row.status === '1' ? 'success' : 'info'">
                    {{ scope.row.status === '1' ? "已发布" : "未发布" }}
                  </el-tag>
                </template>
              </el-table-column>
			  <el-table-column label="更新时间" prop="updateTime" align="left" width="180" />
              <el-table-column label="创建时间" prop="createTime" align="left" width="180" />
              <el-table-column fixed="right" label="操作" width="280">
                <template #default="scope">
                  <el-button
                    type="primary"
                    link
                    icon="Edit"
					:loading="loading"
                    @click="handleEdit(scope.row)"
                  >
                    编辑
                  </el-button>
                  <el-button
                    type="success"
                    link
                    icon="View"
					:loading="loading"
                    @click="handleDesign(scope.row)"
                  >
                    设计
                  </el-button>
                  <el-button
                    type="danger"
                    link
                    icon="Delete"
					:loading="loading"
                    @click="handleDelete(scope.row.id)"
                  >
                    删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>

            <!-- 分页 -->
            <div style="display: flex;justify-content: flex-end;align-items: center">
              <pagination
                v-model:total="total"
                v-model:page="queryParams.cur"
                v-model:limit="queryParams.limit"
                @pagination="handleQuery"
              />
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 流程编辑抽屉 -->
    <el-drawer
      v-model="drawer.visible"
      :title="drawer.title"
      size="500px"
      append-to-body
      destroy-on-close
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="蓝图名称" prop="name">
          <el-input v-model="formData.name" placeholder="请输入蓝图名称" />
        </el-form-item>
        <el-form-item label="蓝图描述" prop="remark">
          <el-input
            v-model="formData.remark"
            type="textarea"
            placeholder="请输入蓝图描述"
          />
        </el-form-item>
		
        <el-form-item label="是否发布" prop="isRelease">
          <el-radio-group v-model="formData.isRelease">
            <el-radio label="1">是</el-radio>
            <el-radio label="0">否</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <div style="flex: auto">
          <el-button @click="drawer.visible = false" :loading="loading">取消</el-button>
          <el-button type="primary" @click="handleSubmit" :loading="loading">确定</el-button>
        </div>
      </template>
    </el-drawer>

    <!-- 流程设计抽屉 -->
    <el-drawer
      v-model="designDrawer.visible"
      :title="designDrawer.title"
      size="100%"
      append-to-body
      destroy-on-close
	  body-class="drawer-blueprint-body"
    >
      <blueprint-designer
        ref="designerRef"
		:nodes="designDrawer.flowData.nodes"
		:groups="designDrawer.flowData.groups"
		:connections="designDrawer.flowData.connections"
      />
	  
	  
	  <template #footer>
	    <div class="dialog-footer">
	  	<el-button type="primary" @click="handleSaveFlow" :loading="loading">确 定</el-button>
	    </div>
	  </template>
    </el-drawer>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import BlueprintDesigner from './components/BlueprintDesigner.vue';
import BlueprintDesignerAPI, { BlueprintDesignerPageVO, BlueprintDesignerPageQuery, BlueprintDesignerForm } from "@/api/biz/blueprintdesigner";
import { useWorkflowStore, type WorkflowStore } from '@/stores/workflow';
const workflowStore: WorkflowStore = useWorkflowStore();
// 表格数据
const loading = ref(false);
const ids = ref<string[]>([]);
const total = ref(0);
const blueprintDesignerList = ref<BlueprintDesignerPageVO[]>();
const queryParams = reactive<BlueprintDesignerPageQuery>({
  cur: 1,
  limit: 10,
  keywords:""
});


// 表单数据
const formRef = ref();
const formData = reactive<BlueprintDesignerForm>({
});

// 抽屉状态
const drawer = reactive({
  visible: false,
  title: ''
});

const designDrawer = reactive({
  visible: false,
  title: '',
  workflowId: '',
  flowData: {
    nodes: [],
    connections: [],
	groups:[]
  }
});

const designerRef = ref();

const rules = reactive({
  name: [{ required: true, message: '请输入蓝图名称', trigger: 'blur' }],
});

// 查询
function handleQuery() {
  loading.value = true;
  BlueprintDesignerAPI.getPage(queryParams)
    .then((data) => {
      blueprintDesignerList.value = data.list;
      total.value = data.totalRow;
    })
    .finally(() => {
      loading.value = false;
    });
}

// 重置查询
function handleResetQuery() {
  queryParams.cur = 1;
  queryParams.keywords = '';
  handleQuery();
}

// 选择变更
const handleSelectionChange = (selection: BlueprintDesignerForm[]) => {
  ids.value = selection.map(item => item.id!);
};

// 新增流程
const handleAdd = () => {
  drawer.title = '新增蓝图信息';
  drawer.visible = true;
  formData.id = undefined;
  formData.name = '';
  formData.remark = '';
  formData.isRelease = '0';
};

// 编辑流程
const handleEdit = (row: BlueprintDesignerForm) => {
  drawer.title = '编辑蓝图信息';
  drawer.visible = true;
  Object.assign(formData, row);
};

// 删除蓝图设计信息
function handleDelete(id?: string) {
  const Ids = [id || ids.value].join(",");
  if (!Ids) {
    ElMessage.warning("请勾选删除需要删除蓝图.");
    return;
  }

  ElMessageBox.confirm("确认删除已选中的蓝图?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(
    () => {
      loading.value = true;
      BlueprintDesignerAPI.deleteByIds(Ids)
        .then(() => {
          ElMessage.success("删除成功");
          handleResetQuery();
        })
        .finally(() => (loading.value = false));
    },
    () => {
      ElMessage.info("已取消删除");
    }
  );
}

// 提交表单
const handleSubmit = () => {
	formRef.value.validate((isValid: boolean) => {
	  if (isValid) {
		   loading.value = true;
			BlueprintDesignerAPI.save(formData)
			.then(() => {
				ElMessage.success("成功");
				handleQuery();
				drawer.title = '';
				drawer.visible = false;
				formData.id = undefined;
				formData.name = '';
				formData.remark = '';
				formData.isRelease = '0';
			})
			.finally(() => (loading.value = false));
	  }
	});
};

// 蓝图设计信息
const handleDesign = (row: any) => {
  loading.value = true;
  BlueprintDesignerAPI.getContentById(row.id)
    .then((data) => {
		designDrawer.workflowId=row.id;
		designDrawer.title = `蓝图 - ${row.name}`;
		if(data && data.content){
			const content=JSON.parse(data.content)
			if(content){
				designDrawer.flowData.nodes=content.nodes;
				designDrawer.flowData.groups=content.groups;
				designDrawer.flowData.connections=content.connections;
			}
		}
		designDrawer.visible=true;
    })
    .finally(() => (loading.value = false));
};

// 保存流程设计
const handleSaveFlow = async () => {
	loading.value = true;
	BlueprintDesignerAPI.saveContent({
		id:designDrawer.workflowId,
		content:JSON.stringify({
			nodes:workflowStore.state.nodes,
			groups:workflowStore.state.groups,
			connections:workflowStore.state.connections
		})
	})
	.then(() => {
		ElMessage.success("成功");
		drawer.title = '';
		drawer.visible = false;
		formData.id = undefined;
		formData.name = '';
		formData.remark = '';
		formData.isRelease = '0';
	})
	.finally(()=>{
		loading.value = false;
		designDrawer.visible = false;
		designDrawer.workflowId="";
		designDrawer.title="";
		designDrawer.flowData= {
			nodes: [],
			connections: [],
			groups:[]
		}
	});
};

onMounted(() => {
  handleQuery();
});
</script>

<style lang="scss" scoped>
.table-tool-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 5px;
}

.workflow-designer {
  height: 100%;
  background-color: #f5f5f5;
}

:deep(.el-drawer__body) {
  padding: 20px;
}

:deep(.el-table th.el-table__cell) {
  background-color: #eee;
  background-image: linear-gradient(to bottom, #f2f2f2 0, #fafafa 100%);
  font-size: 12px;
}

</style>